package com.yanqu.road.server.cmd.curio;

import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.pb.cangbao.CurioProto;
import com.yanqu.road.server.cmd.CrossCommand;
import com.yanqu.road.server.command.Cmd;
import com.yanqu.road.server.logic.MessageHelper;
import com.yanqu.road.server.manager.curio.CrossCurioMgr;
import com.yanqu.road.server.protocol.CrossProtocol;
import com.yanqu.road.server.protocol.Protocol;
import com.yanqu.road.utils.YanQuMessageUtils;

import java.math.BigInteger;
import java.util.HashMap;
import java.util.Map;

@Cmd(code = CrossProtocol.C_CURIO_MAX_SCORE_UPLOAD, desc = "藏品系统单个藏品最高分数上报")
public class CrossCurioUploadMaxScoreCmd extends CrossCommand {

    @Override
    public boolean parseData(YanQuMessage packet) throws Exception {
        return true;
    }

    @Override
    public void execute(YanQuMessage packet) throws Exception {

        CurioProto.CrossCurioUploadMaxScoreMsg maxScoreMsg = CurioProto.CrossCurioUploadMaxScoreMsg.parseFrom(packet.getBytes());
        Map<Integer, BigInteger> scoreMap = new HashMap<>();
        for (CurioProto.CrossCurioMaxScoreTemp scoreTemp : maxScoreMsg.getItemScoreList()) {
            scoreMap.put(scoreTemp.getCurioItemId(), BigInteger.valueOf(scoreTemp.getScore()));
        }
        CrossCurioMgr.changeMaxScore(serverId, scoreMap, maxScoreMsg.getUserList());

        if(maxScoreMsg.getNeedAll()){
            int groupId = CrossCurioMgr.getGroupId(serverId);
            if(CrossCurioMgr.isAllUpload(groupId)) {
                Map<Integer, BigInteger> map = CrossCurioMgr.getGroupScoreMap(groupId);
                if (map != null) {
                    CurioProto.CrossCurioMaxScoreSyncMsg.Builder syncBuilder = CrossCurioMgr.getMaxScoreSyncBuilder(map);
                    syncBuilder.setAllSync(true);
                    MessageHelper.sendPacket(serverId, 0, YanQuMessageUtils.buildMessage(Protocol.S_CURIO_MAX_SCORE_SYNC_FROM_CROSS, syncBuilder));
                    CrossCurioMgr.getLogger().info("分组id : {}， 藏品最高分 同步给 区服： {}, 大小 {}， 全量：{}", groupId, serverId, map.size(), maxScoreMsg.getNeedAll());
                }
            }
        }
    }

    @Override
    public void sendData() {

    }
}
